package com.google.code.chaotic.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.code.chaotic.model.HabitInService;

//

public class PickupCancellingServlet extends HttpServlet {

	protected void doGet( //
			HttpServletRequest request, HttpServletResponse response) //
			throws ServletException, IOException {

		String code = request.getParameter("code");
		// EntityManager em = EmFactory.get().createEntityManager();
		PersistenceManager pm = PmFactory.get().getPersistenceManager();
		try {
			// String jqlStmt = "SELECT h FROM HabitInService h "
			// + "WHERE h.cancellingCode = ?1";
			// Query query = em.createQuery(jqlStmt);
			// query.setParameter(1, code);
			// HabitInService his = (HabitInService) query.getSingleResult();

			Query query = pm.newQuery(HabitInService.class,
					"cancellingCode == code1");
			query.declareParameters("String code1");
			query.setUnique(true);
			HabitInService his = (HabitInService) query.execute(code);

			PrintWriter w = response.getWriter();
			if (his.getCancellationTime() == null) {
				// EntityTransaction tx = em.getTransaction();
				Transaction tx = pm.currentTransaction();
				tx.begin();
				his.setCancellationTime(new Date());
				// em.persist(his);
				pm.makePersistent(his);
				tx.commit();
				w
						.write("<html>"
								+ "<title>Pickup Cancellation</title>" //
								+ "<body><p>Your cancellation request" //
								+ " was received and applied successfully.</p>"//
								+ "\n<p>Hope to have you on the next ride offering!</p>"
								+ "</body>" //
								+ "</html>");
			} else
				w
						.write("<html>"
								+ "<title>Pickup Cancellation</title>" //
								+ "<body><p>The pickup has already been cancelled!</p></body>" //
								+ "</html>");

		} finally {
			// em.close();
			pm.close();
		}

	}
}
